<template>
  <div class="template-manager">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>日志模板管理</span>
        <div style="float: right">
          <el-button
            type="primary"
            size="small"
            @click="openAddDialog"
            style="margin-right: 10px"
            >新增模板</el-button
          >
          <el-button
            type="success"
            size="small"
            @click="refreshTemplates"
            icon="el-icon-refresh"
            :loading="loading"
            >刷新</el-button
          >
        </div>
      </div>

      <!-- 搜索栏 -->
      <div class="search-bar" style="margin-bottom: 15px">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索模板名称或描述..."
          style="width: 300px; margin-right: 10px"
          clearable
          @keyup.enter.native="handleSearch"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-button @click="handleSearch" type="primary" size="small"
          >搜索</el-button
        >
        <el-button @click="resetSearch" size="small">重置</el-button>
      </div>

      <el-table
        :data="pagedTemplates"
        border
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="模板名称" width="150" />
        <el-table-column prop="description" label="描述" width="200" />
        <el-table-column
          prop="sqlTimeoutThreshold"
          label="超时阈值"
          width="100"
        >
          <template slot-scope="scope">
            {{ (scope.row.sqlTimeoutThreshold || 30000) / 1000 }}秒
          </template>
        </el-table-column>
        <el-table-column
          prop="threadMatchingStrategy"
          label="线程匹配"
          width="100"
        >
          <template slot-scope="scope">
            {{ threadMatchText(scope.row.threadMatchingStrategy) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="preparingRegex"
          label="Preparing正则"
          min-width="250"
          show-overflow-tooltip
        />
        <el-table-column
          prop="parametersRegex"
          label="Parameters正则"
          min-width="250"
          show-overflow-tooltip
        />
        <el-table-column
          prop="totalRegex"
          label="Total正则"
          min-width="250"
          show-overflow-tooltip
        />

        <el-table-column label="操作" min-width="300" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="openEditDialog(scope.row)"
              >编辑</el-button
            >
            <el-button size="mini" @click="openTestDialog(scope.row)"
              >测试</el-button
            >
            <el-button size="mini" @click="openRegexTestDialog(scope.row)"
              >正则测试</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="deleteTemplate(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredTemplates.length"
        style="margin-top: 10px; text-align: right"
      />
    </el-card>

    <!-- 弹窗组件 -->
    <template-edit-dialog
      :visible.sync="showEditDialog"
      :edit-mode="editMode"
      :template="currentTemplate"
      @refresh="loadTemplates"
      @close="handleEditDialogClose"
    />
    <template-test-dialog
      :visible.sync="showTestDialog"
      :template="currentTemplate"
      @close="handleTestDialogClose"
    />
    <regex-test-dialog
      :visible.sync="showRegexTestDialog"
      :template="currentTemplate"
      @close="handleRegexTestDialogClose"
    />
  </div>
</template>

<script>
import axios from "axios";
import TemplateEditDialog from "./components/TemplateEditDialog.vue";
import TemplateTestDialog from "./components/TemplateTestDialog.vue";
import RegexTestDialog from "./components/RegexTestDialog.vue";

export default {
  name: "TemplateManager",
  components: {
    TemplateEditDialog,
    TemplateTestDialog,
    RegexTestDialog,
  },
  data() {
    return {
      templates: [],
      page: 1,
      pageSize: 10,
      showEditDialog: false,
      showTestDialog: false,
      showRegexTestDialog: false,
      editMode: false,
      currentTemplate: null,
      apiBaseUrl: "http://localhost:8080/api/template",
      loading: false,
      searchKeyword: "",
    };
  },
  computed: {
    filteredTemplates() {
      if (!this.searchKeyword) {
        return this.templates;
      }
      const keyword = this.searchKeyword.toLowerCase();
      return this.templates.filter(
        (template) =>
          (template.name && template.name.toLowerCase().includes(keyword)) ||
          (template.description &&
            template.description.toLowerCase().includes(keyword))
      );
    },
    pagedTemplates() {
      const start = (this.page - 1) * this.pageSize;
      return this.filteredTemplates.slice(start, start + this.pageSize);
    },
  },
  created() {
    this.loadTemplates();
  },
  methods: {
    async loadTemplates() {
      this.loading = true; // 开始加载
      try {
        const res = await axios.get(this.apiBaseUrl);
        this.templates = res.data;
      } catch (e) {
        this.$message.error("获取模板失败");
      } finally {
        this.loading = false; // 结束加载
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.page = 1; // 重置到第一页
    },
    handleCurrentChange(val) {
      this.page = val;
    },
    openAddDialog() {
      this.editMode = false;
      this.currentTemplate = null;
      this.showEditDialog = true;
    },
    openEditDialog(row) {
      this.editMode = true;
      this.currentTemplate = { ...row };
      this.showEditDialog = true;
    },
    openTestDialog(row) {
      this.currentTemplate = { ...row };
      this.showTestDialog = true;
    },
    openRegexTestDialog(row) {
      this.currentTemplate = { ...row };
      this.showRegexTestDialog = true;
    },
    // 弹窗关闭时的处理
    handleEditDialogClose() {
      this.showEditDialog = false;
      // 延迟重置，避免在弹窗关闭过程中出现null
      this.$nextTick(() => {
        this.currentTemplate = null;
        // 自动刷新模板列表
        this.refreshTemplates();
      });
    },
    handleTestDialogClose() {
      this.showTestDialog = false;
      this.$nextTick(() => {
        this.currentTemplate = null;
      });
    },
    handleRegexTestDialogClose() {
      this.showRegexTestDialog = false;
      this.$nextTick(() => {
        this.currentTemplate = null;
      });
    },
    async deleteTemplate(row) {
      try {
        await this.$confirm("确定要删除该模板吗？", "提示", {
          type: "warning",
        });
        await axios.delete(`${this.apiBaseUrl}/${row.id}`);
        this.$message.success("模板已删除");
        this.loadTemplates();
      } catch (e) {
        // 用户取消或请求失败
      }
    },
    threadMatchText(val) {
      switch (val) {
        case "exact":
          return "精确匹配";
        case "prefix":
          return "前缀匹配";
        case "contains":
          return "包含匹配";
        default:
          return val;
      }
    },
    async refreshTemplates() {
      this.loading = true;
      try {
        await this.loadTemplates();
        this.$message.success("模板列表已刷新");
      } catch (e) {
        this.$message.error("刷新失败");
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      this.page = 1; // 搜索时重置到第一页
      this.loadTemplates();
    },
    resetSearch() {
      this.searchKeyword = "";
      this.page = 1; // 重置到第一页
      this.loadTemplates();
    },
  },
};
</script>

<style scoped>
.template-manager {
  margin: 1% auto;
  width: 100%;
}
.box-card {
  margin-bottom: 20px;
}
.search-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}
</style>